package com.sui.bigdata.sml.web.configuration;

import com.feidee.fdcommon.configuration.CustomConfiguration;
import com.sui.bigdata.sml.web.misc.k8s.KubeClient;
import com.sui.bigdata.sml.web.util.Constants;
import io.kubernetes.client.ApiClient;
import io.kubernetes.client.apis.AppsV1Api;
import io.kubernetes.client.apis.CoreV1Api;
import io.kubernetes.client.apis.ExtensionsV1beta1Api;
import io.kubernetes.client.util.ClientBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;

/**
 * @author songhaicheng
 * @date 2020/3/6 10:04
 * @description
 * @reviewer
 */
@Configuration
@DependsOn("disconfConfig")
@Slf4j
public class KubeConfig {

    public static final String NAME_PREFIX = "sml-model-";
    public static final String INGRESS_NAME_PREFIX = "ingress-" + NAME_PREFIX;
    public static final String CONFIG_FILE_NAME = "/config";

    public static String NAMESPACE;
    public static String TF_IMAGE;
    public static String SML_IMAGE;

    public static AppsV1Api deploymentAPI;
    public static CoreV1Api serviceAPI;
    public static ExtensionsV1beta1Api ingressAPI;

    @Bean
    public KubeClient kubeClient() throws Exception {
        NAMESPACE = CustomConfiguration.getString(Constants.KUBE_NAMESPACE, "bigdata");
        TF_IMAGE = CustomConfiguration.getString(Constants.KUBE_TF_IMAGE);
        SML_IMAGE = CustomConfiguration.getString(Constants.KUBE_SML_IMAGE);
        // 读取 resources 目录下的 config 文件
        InputStream configStream = this.getClass().getResourceAsStream(CONFIG_FILE_NAME);
        if (configStream == null) {
            throw new Exception("未在 resources 目录下读取到 k8s config 配置文件");
        }
        // 通过配置文件初始化 client 对象与集群上的 k8s 通信
        Reader configReader = new InputStreamReader(configStream);
        ApiClient apiClient = ClientBuilder.kubeconfig(io.kubernetes.client.util.KubeConfig.loadKubeConfig(configReader)).build();
        io.kubernetes.client.Configuration.setDefaultApiClient(apiClient);
        // 初始化 API
        deploymentAPI = new AppsV1Api();
        serviceAPI = new CoreV1Api();
        ingressAPI = new ExtensionsV1beta1Api();
        return new KubeClient();
    }

}
